import axios from 'axios'
import store from '../store'
import { Toast } from 'mint-ui'
import codeMessage from 'utils/codeMessage'

const Message = (options) => {
  Toast({
    message: options.message
  })
  options.onClose && setTimeout(options.onClose, options.duration)
}

// 创建axios实例
const service = axios.create({
  baseURL: '/api', // process.env.BASE_API, // api的base_url
  timeout: 10 * 1000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(config => {
  if (config.method.toLowerCase() === 'get') {
    config.params = Object.assign({orgUserId: store.state.orgUserId}, config.params)
  }
  if (config.data && typeof config.data === 'object' && !config.data.orgUserId) {
    config.data.orgUserId = store.state.orgUserId
  }
  // console.log('config', config)
  store.loader.timer && clearTimeout(store.loader.timer)
  store.loader.fetchCount++
  // Do something before request is sent
  // console.log(store.getters)
  config.headers = store.getHeaders()
  // context default action
  if (/^(post)|(put)|(delete)$/i.test(config.method)) { // 处理POST请求默认行为
    if (typeof config.data === 'object') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.transformRequest = [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }]
    } else {
      config.headers['Content-Type'] = 'application/json'
    }
    // console.log('context', config.context)
    if (config.options && config.options.context) {
      if (config.options.context._isVue) { // context为vue对象则修改loading状态
        config.options.context.loading = true
        config.options.successMsg = config.options.successMsg || '提交成功'
        config.options.errorMsg = config.options.errorMsg || '提交失败'
      } else if (config.options.context.nodeType === 1) { // context为dom对象则修改disabled状态
        if (config.options.context.parentNode.disabled !== undefined) {
          config.options.context = config.options.context.parentNode
        }
        config.options.context.disabled = true
        config.options.successMsg = config.options.successMsg || '操作成功'
        config.options.errorMsg = config.options.errorMsg || '操作失败'
      }
    }
  }
  let orgId = localStorage.getItem('auth_orgId') || ''
  if (orgId && config.url !== '/api/user/authServiceList') {
    config.params = Object.assign({authOrgId: orgId}, config.params)
  }
  let userAgent = navigator.userAgent
  if (userAgent.indexOf('Trident') > -1) {
    config.params = Object.assign({_: new Date().getTime()}, config.params)
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})
// response拦截器
service.interceptors.response.use(
  res => {
    // console.log('res', res)
    store.loader.fetchCount === 1 && store.loader.onComplete && store.loader.onComplete()
    store.loader.fetchCount = store.loader.fetchCount > 0 ? store.loader.fetchCount - 1 : 0
    // context default action
    if (/^(post)|(put)|(delete)$/i.test(res.config.method)) {
      // console.log('res.context', res.config.context)
      if (res.config.options && res.config.options.context) { // 是否传上下文
        if (res.config.options.context._isVue) { // context为vue对象时则修改loading状态
          res.config.options.context.loading = false
          res.config.options.context = null
        } else if (res.config.options.context.nodeType === 1) { //  context为元素对象时则修改disabled状态
          res.config.options.context.disabled = false
        }
      }
    }
    if (res.data.result === '0') { // 成功后返回数据
      // context default action
      if (/^(post)|(put)|(delete)$/i.test(res.config.method)) {
        if ((res.config.options || {}).successMsg !== 'none') { // successMsg为'none'时不提示弹框
          Message({
            message: res.config.options && res.config.options.successMsg ? res.config.options.successMsg : '提交成功',
            type: 'success',
            duration: 2 * 1000
          })
        }
      }
      return res.data
    } else {
      if (['22', '2103', '2125', '2102'].indexOf(res.data.result) > -1) { // 未登录，签名错误
        store.commit('RESET_INFO')
        localStorage.removeItem('menuKey')
        Message({
          message: '登录超时',
          type: 'error',
          duration: 2 * 1000,
          onClose () {
            location.href = '/login'
          }
        })
      } else if ((res.config.options || {}).errorMsg !== 'none') { // errorMsg为'none'时不提示弹框
        Message({
          message: res.data.msg || codeMessage[res.data.result] || res.config.options.errorMsg,
          type: 'error',
          duration: 2 * 1000,
          onClose () {
            if (window.location.pathname !== '/' && res.data.result === '1009') {
              location.href = '/'
            }
          }
        })
      }
      return Promise.reject(res.data)
    }
  }
  /**
   * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
   * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
   */
  ,
  error => {
    store.loader.fetchCount === 1 && store.loader.onComplete && store.loader.onComplete()
    store.loader.fetchCount = store.loader.fetchCount > 0 ? store.loader.fetchCount - 1 : 0
    console.log('err', error)// for debug
    /*
     Message({
     message: error.message,
     type: 'error',
     duration: 5 * 1000
    });
    */
    return Promise.reject(error)
  }
)
export default service
